package com.skywork.utils;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;

public class RSAUtils {

	/**
	 * 加密算法RSA
	 */
	public static final String KEY_ALGORITHM = "RSA";

	/**
	 * 签名算法
	 */
	public static final String SIGNATURE_ALGORITHM = "MD5withRSA";

	/**
	 * 获取公钥的key
	 */
	private static final String PUBLIC_KEY = "RSAPublicKey";

	/**
	 * 获取私钥的key
	 */
	private static final String PRIVATE_KEY = "RSAPrivateKey";

	/**
	 * RSA最大加密明文大小
	 */
	private static final int MAX_ENCRYPT_BLOCK = 117;

	/**
	 * RSA最大解密密文大小
	 */
	private static final int MAX_DECRYPT_BLOCK = 128;

	private static Key publicKey;

	private static PrivateKey privateKey;

	/**
	 * <p>
	 * 生成密钥对(公钥和私钥)
	 * </p>
	 * 
	 * @return
	 * @throws Exception
	 */
	public static Map<String, Object> genKeyPair() throws Exception {
		KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
		keyPairGen.initialize(1024);
		KeyPair keyPair = keyPairGen.generateKeyPair();
		saveKeyPair(keyPair);
		RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
		RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
		Map<String, Object> keyMap = new HashMap<String, Object>(2);
		keyMap.put(PUBLIC_KEY, publicKey);
		keyMap.put(PRIVATE_KEY, privateKey);
		return keyMap;
	}

	/**
	 * 保存秘钥到文件
	 * 
	 * @param kp
	 * @throws Exception
	 */
	public static void saveKeyPair(KeyPair kp) throws Exception {

		FileOutputStream fos = new FileOutputStream("C:/RSAKey.txt");
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		// 生成密钥
		oos.writeObject(kp);
		oos.close();
		fos.close();
	}

	/**
	 * <p>
	 * 用私钥对信息生成数字签名
	 * </p>
	 * 
	 * @param data
	 *            已加密数据
	 * @param privateKey
	 *            私钥(BASE64编码)
	 * 
	 * @return
	 * @throws Exception
	 */
	public static String sign(byte[] data, String privateKey) throws Exception {
		byte[] keyBytes = Base64.decodeBase64(privateKey);
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
		Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
		signature.initSign(privateK);
		signature.update(data);
		return Base64.encodeBase64String(signature.sign());
	}

	/**
	 * <p>
	 * 校验数字签名
	 * </p>
	 * 
	 * @param data
	 *            已加密数据
	 * @param publicKey
	 *            公钥(BASE64编码)
	 * @param sign
	 *            数字签名
	 * 
	 * @return
	 * @throws Exception
	 * 
	 */
	public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {
		byte[] keyBytes = Base64.decodeBase64(publicKey);
		X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		PublicKey publicK = keyFactory.generatePublic(keySpec);
		Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
		signature.initVerify(publicK);
		signature.update(data);
		return signature.verify(Base64.decodeBase64(sign));
	}

	/**
	 * <P>
	 * 私钥解密
	 * </p>
	 * 
	 * @param encryptedData
	 *            已加密数据
	 * @param privateKey
	 *            私钥(BASE64编码)
	 * @return
	 * @throws Exception
	 */
	public static String decryptByPrivateKey(String encryptedData, String privateKey) throws Exception {
		byte[] keyBytes = Base64.decodeBase64(privateKey);
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.DECRYPT_MODE, privateK);
		byte[] sourceDate = Base64.decodeBase64(encryptedData);
		int inputLen = sourceDate.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		byte[] cache;
		int i = 0;
		// 对数据分段解密
		while (inputLen - offSet > 0) {
			if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
				cache = cipher.doFinal(sourceDate, offSet, MAX_DECRYPT_BLOCK);
			} else {
				cache = cipher.doFinal(sourceDate, offSet, inputLen - offSet);
			}
			out.write(cache, 0, cache.length);
			i++;
			offSet = i * MAX_DECRYPT_BLOCK;
		}
		byte[] decryptedData = out.toByteArray();
		out.close();
		return new String(decryptedData);
	}

	/**
	 * <p>
	 * 公钥解密
	 * </p>
	 * 
	 * @param encryptedData
	 *            已加密数据
	 * @param publicKey
	 *            公钥(BASE64编码)
	 * @return
	 * @throws Exception
	 */
	public static String decryptByPublicKey(String encryptedData, String publicKey) throws Exception {
		byte[] keyBytes = Base64.decodeBase64(publicKey);
		X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		Key publicK = keyFactory.generatePublic(x509KeySpec);
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.DECRYPT_MODE, publicK);
		byte[] data = Base64.decodeBase64(encryptedData);
		int inputLen = data.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		byte[] cache;
		int i = 0;
		// 对数据分段解密
		while (inputLen - offSet > 0) {
			if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
				cache = cipher.doFinal(data, offSet, MAX_DECRYPT_BLOCK);
			} else {
				cache = cipher.doFinal(data, offSet, inputLen - offSet);
			}
			out.write(cache, 0, cache.length);
			i++;
			offSet = i * MAX_DECRYPT_BLOCK;
		}
		byte[] decryptedData = out.toByteArray();
		out.close();
		return new String(decryptedData);
	}

	/**
	 * <p>
	 * 公钥加密
	 * </p>
	 * 
	 * @param data
	 *            源数据
	 * @param publicKey
	 *            公钥(BASE64编码)
	 * @return
	 * @throws Exception
	 */
	public static String encryptByPublicKey(String data, String publicKey) throws Exception {
		byte[] keyBytes = Base64.decodeBase64(publicKey);
		X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		Key publicK = keyFactory.generatePublic(x509KeySpec);
		// 对数据加密
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.ENCRYPT_MODE, publicK);
		byte[] sourceData = data.getBytes();
		int inputLen = sourceData.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		byte[] cache;
		int i = 0;
		// 对数据分段加密
		while (inputLen - offSet > 0) {
			if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
				cache = cipher.doFinal(sourceData, offSet, MAX_ENCRYPT_BLOCK);
			} else {
				cache = cipher.doFinal(sourceData, offSet, inputLen - offSet);
			}
			out.write(cache, 0, cache.length);
			i++;
			offSet = i * MAX_ENCRYPT_BLOCK;
		}
		byte[] encryptedData = out.toByteArray();
		out.close();
		return Base64.encodeBase64String(encryptedData);
	}

	/**
	 * <p>
	 * 私钥加密
	 * </p>
	 * 
	 * @param data
	 *            源数据
	 * @param privateKey
	 *            私钥(BASE64编码)
	 * @return
	 * @throws Exception
	 */
	public static byte[] encryptByPrivateKey(byte[] data, String privateKey) throws Exception {
		byte[] keyBytes = Base64.decodeBase64(privateKey);
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.ENCRYPT_MODE, privateK);
		int inputLen = data.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		byte[] cache;
		int i = 0;
		// 对数据分段加密
		while (inputLen - offSet > 0) {
			if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
				cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
			} else {
				cache = cipher.doFinal(data, offSet, inputLen - offSet);
			}
			out.write(cache, 0, cache.length);
			i++;
			offSet = i * MAX_ENCRYPT_BLOCK;
		}
		byte[] encryptedData = out.toByteArray();
		out.close();
		return encryptedData;
	}

	public static String encryptByPrivateKey(String data, String privateKey) throws Exception {
		byte[] keyBytes = Base64.decodeBase64(privateKey);
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.ENCRYPT_MODE, privateK);
		byte[] sourceData = data.getBytes();
		int inputLen = sourceData.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		byte[] cache;
		int i = 0;
		// 对数据分段加密
		while (inputLen - offSet > 0) {
			if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
				cache = cipher.doFinal(sourceData, offSet, MAX_ENCRYPT_BLOCK);
			} else {
				cache = cipher.doFinal(sourceData, offSet, inputLen - offSet);
			}
			out.write(cache, 0, cache.length);
			i++;
			offSet = i * MAX_ENCRYPT_BLOCK;
		}
		byte[] encryptedData = out.toByteArray();
		out.close();
		return Base64.encodeBase64String(encryptedData);
	}

	/**
	 * <p>
	 * 获取私钥
	 * </p>
	 * 
	 * @param keyMap
	 *            密钥对
	 * @return
	 * @throws Exception
	 */
	public static String getPrivateKey(Map<String, Object> keyMap) throws Exception {
		Key key = (Key) keyMap.get(PRIVATE_KEY);
		return Base64.encodeBase64String(key.getEncoded());
	}

	/**
	 * <p>
	 * 获取公钥
	 * </p>
	 * 
	 * @param keyMap
	 *            密钥对
	 * @return
	 * @throws Exception
	 */
	public static String getPublicKey(Map<String, Object> keyMap) throws Exception {
		Key key = (Key) keyMap.get(PUBLIC_KEY);
		return Base64.encodeBase64String(key.getEncoded());
	}

	public void setPrivateKey(String privateKey) throws Exception {
		byte[] keyBytes = Base64.decodeBase64(privateKey);
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		RSAUtils.privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
	}

	public void setPublicKey(String publicKey) throws Exception {
		byte[] keyBytes = Base64.decodeBase64(publicKey);
		X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		RSAUtils.publicKey = keyFactory.generatePublic(x509KeySpec);
	}

	public static byte[] encrypt(byte[] data) throws Exception {
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.ENCRYPT_MODE, privateKey);
		int inputLen = data.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		byte[] cache;
		int i = 0;
		// 对数据分段加密
		while (inputLen - offSet > 0) {
			if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
				cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
			} else {
				cache = cipher.doFinal(data, offSet, inputLen - offSet);
			}
			out.write(cache, 0, cache.length);
			i++;
			offSet = i * MAX_ENCRYPT_BLOCK;
		}
		byte[] encryptedData = out.toByteArray();
		out.close();
		return encryptedData;
	}

	public static String encryptByPublicKey(byte[] data) throws Exception {
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		// 对数据加密
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.ENCRYPT_MODE, publicKey);
		int inputLen = data.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		byte[] cache;
		int i = 0;
		// 对数据分段加密
		while (inputLen - offSet > 0) {
			if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
				cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
			} else {
				cache = cipher.doFinal(data, offSet, inputLen - offSet);
			}
			out.write(cache, 0, cache.length);
			i++;
			offSet = i * MAX_ENCRYPT_BLOCK;
		}
		byte[] encryptedData = out.toByteArray();
		out.close();
		return Base64.encodeBase64String(encryptedData);
	}

	public static String decrypt(byte[] encryptedData) throws Exception {
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.DECRYPT_MODE, publicKey);
		int inputLen = encryptedData.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		byte[] cache;
		int i = 0;
		// 对数据分段解密
		while (inputLen - offSet > 0) {
			if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
				cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
			} else {
				cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
			}
			out.write(cache, 0, cache.length);
			i++;
			offSet = i * MAX_DECRYPT_BLOCK;
		}
		byte[] decryptedData = out.toByteArray();
		out.close();
		return new String(decryptedData);
	}

//	public static void main(String[] args) throws Exception {
//		String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCfdzjkQj6xEHhYLLY1Xrm4KXPhEyus1FMNa7FL0r3CKgYPLW2NeuKIPAT/+0aY5JtBzGaw1EIWHP/M2pAy25I8HH7RQx7K2Qyhzs5xT8+9/Rrti6bQE8HXSklkCeUOqkuv5nLlzoam0hg1258P7hbJTMhZ9UTzHITTc47quIXzfQIDAQAB";
//		String privateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAJ93OORCPrEQeFgstjVeubgpc+ETK6zUUw1rsUvSvcIqBg8tbY164og8BP/7Rpjkm0HMZrDUQhYc/8zakDLbkjwcftFDHsrZDKHOznFPz739Gu2LptATwddKSWQJ5Q6qS6/mcuXOhqbSGDXbnw/uFslMyFn1RPMchNNzjuq4hfN9AgMBAAECgYBCxvY3/9Wo6DC9G9whdU1oZVN1SUXc1f0Bfbt8+P8ls9tdt7RMrsz2J8wgNeVWWUT6xNGr8vbJs9MawdvosDIH+ICoXcP4y9PGzScnjTaXeLGL7Atnhxg3jZseNZfkXHPZj9pQVCY5jaayUUbBLguD1KKXR1Ab6qG2TSBmbemGMQJBANfLz4/X60q/cSlQZG5Y5ZJUSeYfw94EEZeeW0/1ywDEXyj036N6JSP4/YUPaUhjkUpptghYmYewfRZunRBssLMCQQC9LMk5X8+zMrYHh+53vQYE+nXZePwkbkWzF0dnh4SLkJZeKQ/rx9YB2TjvdQY76cB/FQ+qcDgMn8r5xoizVIMPAkBQkRNJTP/XxGnnVtBoMmBjpXyBolJqTXKT/Ndynv3Pp4EvtVzZl/zN1WQxjXNtR18zPQxtSUbo1gednGaffzTpAkBUhI3idEv3Y9CvzKteE7V8w+mjH8qG/D1nph7gwksVj6OerfnO/Zk/ei1VzpLacbTvEhnNrBVejoXA0lKAzGFBAkBy6pYc2ka7ThflFqJfiHs4AklVY8jNUZxVQzmbIax6vQx4SDtenmDboCucrHDk6XPlS2hDlHjDis6brJ6M7iBD";
//		String data = "kwHZ2z/SJih7aYBkR0upTqRc2ZOfn6bZRZMqR42Q/SxRlp9EXTk7GHR3tszmwZMD0";
//		//
//		String encryptStr = RSAUtils.encryptByPrivateKey(data, privateKey);// .encryptByPublicKey(data.getBytes());
//		System.out.println(encryptStr + "\r\n");
//		System.out.println(RSAUtils.decryptByPublicKey("A+Tq9kg3y9NQkaJ2nxyASKkOw594SRZULZPq69tnHSYSspc/MZYoIYeNvGntvYo30cnUHfhp58mJ7u+/LVkVElrXPNPCPATPR9G4Z51/gXSHwBiBzx1P9S3c2Ds+FE61sgDNeiZf3uRosPA6yxSOF3wmQBmfUUlAkqP6NEGcSqk=", publicKey));
//
//		String encryptStr2 = RSAUtils.encryptByPublicKey(data, publicKey);// .encryptByPublicKey(data.getBytes());
//		System.out.println(encryptStr2 + "\r\n");
//		System.out.println(RSAUtils.decryptByPrivateKey(encryptStr2, privateKey));
//		System.out.println(RSAUtils.decryptByPrivateKey("R2QtdY9KWbL7B7nBidAnGrlqRwql9VkIWXi2IOXYIOBe0E+ELNRn3SCFaKyQhCujzw7BhOIPw2gkLWZypcd58+IUx09FfezDcMKVADUrEKH1at8QC67cKAnIhiUQfyD3GhPfDsjS1oMLlpbWi/nPAkQqH58SCe+oQstm+cyQFjFB0m8xk/oG5TKS/L9OFYCOK8ueWw/HV91nuWhAOUl6Etdlo5IayijOWLzkVn8EYR2jHKICH+RgasCbJqDtXkX+U1hgVed8ACvIrW/FGDguR0oNE37gaUZeBlfrFxuC5xzzJM0zZpRk74C3SCbJW0l5R6b/P3cVdk79R7xrBI6awA==",
//				"MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAMdWpzdnKwACJXy4ZcUtjdSphBPkSBy8/D6D0I1p4l+BIM18Z/NmHBqSbz/qDgHXiU6bVN4oUN8U8r1fZr3BTgEfG3egR5h1yoQPJLyWkz4MXycsN7u610VNvHGFEGS5NkfU1VmiyajGXc7zSSSfQti09+CG9C0vvryi2nFq3YAZAgMBAAECgYEAmSCPw5eVCKSdd3mPdDDSSxMNStqKKsliXAOWKYu1QfhH4pI2qFtAK4lhvI9nwzJ3X9MjFqWRuky1S5QFsK7V49tNF22jJCvT3G1y/PFPSYkko5fsx81a7/j3AirDiFSgluvAuEL7G4AgUusR0gZMUrs3Lv0rNbYamPUjRwbCwiECQQDrZVxMA+O/xYrSt1zWsXxH7tpYZHOvw4WoP2Y3PKyC/S3XMOL484e75BpxODC96F77Q8FgyczAvV1FHZVM42MnAkEA2MlVpowbeWfoBY1/yJtI0roHcdMzkf/Jy++0mwyyWmIMYa064rCrnyRNU3aghq+StJFzdPOltIavoR+HVFEKvwJBALAVonU6c6OAodf+UfRH0C/+/FYizmcsW08AHfYz7NgPi7rtVtvjUCW8/Aq1fcCRkntis8UzL3b+MEcDWiup7QECQQDH+rJwOL7/d8KpnKZMQDMlcUZ80f+4puVYo39PqJ6+kcQqNssjYyZuX+aVH9FlbYE/4Q1IzZoGtlg9ogAM39WxAkBlxKhZsLl1us+DaNe1M/5+6PsXJogbXzM9bUaSazhwYgC+56EdW3AR1J8p6jgj7h+bjpKjeN2Y8vw1jmsERvhC"));
//	}
}
